<?php
require("../cnFrame/Frame.php");
header("Content-type: application/json; charset=utf-8");
$HOST = 'https://wx-hwbl.z-yd.cn/';
// API密钥验证
$api_key = isset($_GET['key']) ? $_GET['key'] : '';
if($api_key !== 'cih1996') { // 替换为实际的API密钥
    $outJson->msg = "无效的API密钥";
    $outJson->code = 403;
    echo json_encode($outJson);
    exit;
}

/**
 * 添加用户
 * POST /api.php?action=add_user&key=your_api_key
 */
if($_GET['action'] == 'add_user') {
    // 获取POST数据
    $username = '';
    if($_SERVER['REQUEST_METHOD'] === 'POST') {
        $postJson = json_decode(file_get_contents('php://input'), true);
        if(!isset($postJson['username'])) {
            $outJson->msg = "缺少必要参数";
            $outJson->code = 400;
            echo json_encode($outJson);
            exit;
        }
        $username = $postJson['username'];
    } else {
        if(!isset($_GET['username'])) {
            $outJson->msg = "缺少必要参数"; 
            $outJson->code = 400;
            echo json_encode($outJson);
            exit;
        }
        $username = $_GET['username'];
    }

    
    // 检查用户名是否已存在
    $existUser = $cnSql->read_only("users", "user = '$username'");
    if($existUser) {
        $outJson->msg = "用户名已存在";
        $outJson->code = 400;
        echo json_encode($outJson);
        exit;
    }

    // 添加用户
    $result = $cnSql->insert_json("users", array(
        'user' => $username,
        'type' => 0,
        'balance' => 0
    ));

    if($result) {
        $outJson->msg = "用户添加成功";
        $outJson->code = 200;
    } else {
        $outJson->msg = "用户添加失败";
        $outJson->code = 500;
    }
    echo json_encode($outJson);
    exit;
}

/**
 * 搜索数据
 * GET /api.php?action=search&key=your_api_key&template_id=1&keyword=xxx
 */
if($_GET['action'] == 'search') {
    $template_id = isset($_GET['template_id']) ? intval($_GET['template_id']) : 0;
    $keyword = isset($_GET['keyword']) ? trim($_GET['keyword']) : '';

    if(!$template_id || !$keyword) {
        $outJson->msg = "缺少必要参数";
        $outJson->code = 400;
        echo json_encode($outJson);
        exit;
    }

    // 先在releases表中搜索
    $releases = $cnSql->custom("SELECT id, data 
        FROM releases 
        WHERE template_id = $template_id 
        AND data LIKE '%$keyword%'
    ");

    if(!$releases) {
        $outJson->msg = "未找到匹配数据";
        $outJson->code = 404;
        echo json_encode($outJson);
        exit;
    }

    // 获取所有匹配的release ids
    $release_ids = array_column($releases, 'id');
    $release_ids_str = implode(',', $release_ids);

    // 在submit_details表中查找对应的数据
    $details = $cnSql->custom("SELECT 
            d.*,
            u.user as username,
            r.data as release_data,
            t.name as template_name
        FROM submit_details d
        LEFT JOIN users u ON d.user_id = u.id
        LEFT JOIN releases r ON d.task_id = r.id
        LEFT JOIN templates t ON d.template_id = t.id
        WHERE d.task_id IN ($release_ids_str)
        ORDER BY d.create_time DESC
    ");
    // 处理返回数据
    $result = array();
    foreach($details as $detail) {
        $image_paths = json_decode($detail['image_paths'], true);
        // 给图片路径加上域名
        if(is_array($image_paths)) {
            foreach($image_paths as &$path) {
                $path = $HOST . $path['url'];
            }
        }
        
        $result[] = array(
            'id' => intval($detail['id']),
            'task_id' => intval($detail['task_id']), 
            'template_id' => intval($detail['template_id']),
            'template_name' => $detail['template_name'],
            'username' => $detail['username'],
            'release_data' => $detail['release_data'],
            'out_structure' => json_decode($detail['out_structure'], true) ?: array(),
            'image_paths' => $image_paths,
            'status' => intval($detail['status']),
            'create_time' => $detail['create_time']
        );
    }

    $outJson->data = $result;
    $outJson->total = count($result);
    $outJson->msg = "搜索成功";
    $outJson->code = 200;
    echo json_encode($outJson);
    exit;
}

/**
 * 获取一条待审核的爆料数据
 */
if($_GET['action'] == 'get_pending_release'){
    // 从Redis获取当前索引
    $redis = new Redis();
    $redis->connect('127.0.0.1', 6379);
    $current_index = $redis->get('pending_release_index') ?: 0;
    
    // 获取一条待审核的提交数据(status=0)
    $detail = $cnSql->custom("SELECT 
            d.*,
            u.user as username, 
            t.name as template_name,
            r.data as release_data
        FROM submit_details d
        LEFT JOIN users u ON d.user_id = u.id 
        LEFT JOIN templates t ON d.template_id = t.id
        LEFT JOIN releases r ON d.task_id = r.id
        WHERE d.status = 0
        ORDER BY d.id ASC
        LIMIT $current_index,1
    ")[0];

    if($detail){
        // 处理图片路径
        $image_paths = json_decode($detail['image_paths'], true);
        if(is_array($image_paths)) {
            foreach($image_paths as &$path) {
                $path = $HOST . $path['url'];
            }
        }

        $result = array(
            'id' => intval($detail['id']),
            'task_id' => intval($detail['task_id']),
            'template_id' => intval($detail['template_id']), 
            'template_name' => $detail['template_name'],
            'username' => $detail['username'],
            'release_data' => $detail['release_data'],
            'out_structure' => json_decode($detail['out_structure'], true) ?: array(),
            'image_paths' => $image_paths,
            'status' => intval($detail['status']),
            'create_time' => $detail['create_time']
        );

        // 索引递增
        $redis->set('pending_release_index', $current_index + 1);
        
        $outJson->data = $result;
        $outJson->code = 200;
    } else {
        // 如果没有数据,重置索引
        $redis->set('pending_release_index', 0);
        
        // 再次尝试获取第一条数据
        $detail = $cnSql->custom("SELECT 
                d.*,
                u.user as username,
                t.name as template_name, 
                r.data as release_data
            FROM submit_details d
            LEFT JOIN users u ON d.user_id = u.id 
            LEFT JOIN templates t ON d.template_id = t.id
            LEFT JOIN releases r ON d.task_id = r.id
            WHERE d.status = 0
            ORDER BY d.id ASC
            LIMIT 1
        ")[0];

        if($detail) {
            // 处理图片路径
            $image_paths = json_decode($detail['image_paths'], true);
            if(is_array($image_paths)) {
                foreach($image_paths as &$path) {
                    $path = $HOST . $path['url'];
                }
            }

            $result = array(
                'id' => intval($detail['id']),
                'task_id' => intval($detail['task_id']),
                'template_id' => intval($detail['template_id']),
                'template_name' => $detail['template_name'], 
                'username' => $detail['username'],
                'release_data' => $detail['release_data'],
                'out_structure' => json_decode($detail['out_structure'], true) ?: array(),
                'image_paths' => $image_paths,
                'status' => intval($detail['status']),
                'create_time' => $detail['create_time']
            );

            $redis->set('pending_release_index', 1);
            
            $outJson->data = $result;
            $outJson->code = 200;
        } else {
            $outJson->data = null;
            $outJson->code = 200;
            $outJson->msg = "暂无待审核数据";
        }
    }
    
    echo json_encode($outJson);
    exit;
}


//提交审核结果
if($_GET['action'] == 'audit'){
    $id = isset($_GET['id']) ? $_GET['id'] : 0;
    $status = isset($_GET['status']) ? $_GET['status'] : 0;
    //检查是否已经审核过
    $detail = $cnSql->read_only("submit_details", "id = $id");
    if(!$detail){
        $outJson->msg = "记录不存在";
        $outJson->code = 400;
        echo json_encode($outJson);
        exit;
    }
    if($detail['status'] != 0){
        $outJson->msg = "该记录已审核,不能重复审核";
        $outJson->code = 400;
        echo json_encode($outJson);
        exit;
    }
    if($status == 1){
        $user_id = $detail['user_id'];
        $template = $cnSql->read_only("templates", "id = $detail[template_id]");
        $cnSql->custom("UPDATE releases SET status = 3 WHERE id = $detail[task_id]");
        $cnSql->custom("UPDATE users SET balance = balance + $template[price] WHERE id = $user_id");
        $cnSql->update_json("submit_details", array("status" => $status,"price" => $template[price]), "id = $id");

    }else{
        $cnSql->custom("UPDATE releases SET status = 4 WHERE id = $detail[task_id]");
        $cnSql->update_json("submit_details", array("status" => $status,"price" => 0), "id = $id");
    }
    
    $outJson->msg = "审核成功";
    $outJson->code = 200;
    echo json_encode($outJson);
    exit;
}

//上传视频封面图片
if($_GET['action'] == 'upload_video_cover'){
    $file = $_FILES['file'];
    $file_name = $file['name'];
    $file_tmp_name = $file['tmp_name'];
    $file_size = $file['size'];
    $file_error = $file['error'];
    $file_type = $file['type'];
    $file_ext = strtolower(end(explode('.', $file_name)));
    exit;
}

//添加视频
if($_GET['action'] == 'add_video'){
    $postJson = json_decode(file_get_contents("php://input"));
    $cover = isset($postJson->cover) ? $postJson->cover : '';
    $description = isset($postJson->description) ? $postJson->description : '';
    $likes = isset($postJson->likes) ? $postJson->likes : 0;
    $comments = isset($postJson->comments) ? $postJson->comments : 0;
    $duration = isset($postJson->duration) ? $postJson->duration : 0;
    $user_id = $postJson->user_id;
    $url = isset($postJson->url) ? $postJson->url : '';
    $cnSql->insert_json("video_feeds", array("cover" => $cover, "description" => $description, "likes" => $likes, "comments" => $comments, "duration" => $duration, "user_id" => $user_id, "url" => $url));
    $outJson->msg = "添加成功";
    $outJson->code = 200;
    echo json_encode($outJson);
    exit;
}



// 未知的action
$outJson->msg = "未知的操作";
$outJson->code = 400;
echo json_encode($outJson); 